<script lang="ts" setup>
import { provide, ref } from 'vue';
import { message } from 'ant-design-vue';
import ExcelJS from 'exceljs';
import add_record from './components/add_record.vue';
import edit from './components/edit.vue';
import { useUpload } from './useUpload';
import { useDownload } from './usedownload';
import useUserStore from '@/store/modules/user';
// 获取用户信息
const userStore = useUserStore();
const orgName = userStore.userOrgName;
const { auth } = useAuth();
// 数据处理
const data = ref<VAPI.DataItem[]>([]);
const dataIsReady = ref(false);
const loading = ref(false);
const total = ref<number>(0);
const keyWord = ref<string>('');
const current = ref<number>(1);
const pageSize = ref<number>(10);
async function getAllData() {
  data.value = [];
  loading.value = true;
  if (keyWord.value === '') {
    if (auth(['v-getall'])) {
      await getPage(current.value, pageSize.value).then((res: any) => {
        data.value = res.data.records;
        total.value = res.data.total;
        dataIsReady.value = true;
      }).finally(() => {
        loading.value = false;
      });
    }
    else {
      await getPageByArea(current.value, pageSize.value, orgName).then((res: any) => {
        data.value = res.data.records;
        total.value = res.data.total;
        dataIsReady.value = true;
      }).finally(() => {
        loading.value = false;
      });
    }
  }
}

onMounted(async () => {
  getAllData();
});

provide('data', data);
provide('total', total);
provide('current', current);
provide('pageSize', pageSize);
provide('keyWord', keyWord);
// 选中的数据
const selectedId = ref<number[]>([]);

function clearSelected() {
  selectedId.value = [];
}

const isSelected = computed(() => {
  return selectedId.value.length > 0;
});

// 全选功能
let flag = true;
function selectAll() {
  if (flag) {
    const allIds = data.value.map((item: { id: any }) => item.id);
    selectedId.value = allIds;
    flag = !flag;
  }
  else {
    selectedId.value = [];
    flag = !flag;
  }
}
provide('selectedId', selectedId);
// 新增
const visible = ref<boolean>(false);

function add() {
  visible.value = true;
}

function getVisible() {
  visible.value = !visible.value;
}

// 批量删除
async function clearChoose(selectedId: number[]) {
  loading.value = true;
  try {
    const res: any = await deleteRecordById(selectedId);
    if (res) {
      message.success('删除成功');
      getAllData();
      clearSelected();
    }
  }
  catch (error) {
    message.error('删除失败');
  }
  finally {
    loading.value = false;
  }
}

// 搜索
const value = ref<string>('');

async function getDataByKeyword(keyword: string) {
  loading.value = true;
  try {
    let res: any = {};
    if (auth(['v-getall'])) {
      res = await getRecordByKeyword(keyword);
    }
    else {
      res = await getRecordByKeyAndOrg(keyword, orgName);
    }
    if (res) {
      if (res.data === '未查到相关记录') {
        message.error('未查到相关记录');
        return;
      }
      total.value = res.data.length;
      message.success('查询成功');
      current.value = 1;
      pageSize.value = 10;
      data.value = res.data;
    }
  }
  finally {
    loading.value = false;
  }
}

async function onSearch(searchValue: string) {
  keyWord.value = searchValue;
  await getDataByKeyword(searchValue);
}

// excel文件上传
const fileList = ref<any>([]);

// 移除文件
function handleRemove(file: any) {
  const index = fileList.value.findIndex((f: { uid: any }) => f.uid === file.uid);
  fileList.value.splice(index, 1);
}

// 阻止自动上传
function beforeUpload(file: any) {
  fileList.value = [];
  fileList.value.push(file);
  return false; // 阻止自动上传
}

// 手动上传
async function handleManualUpload() {
  if (fileList.value.length === 0) {
    message.error('请上传文件！');
    return;
  }
  fileList.value.forEach(async (file: any) => {
    // 判断文件类型
    if (useUpload().checkIfExcel(file.name || '')) {
      loading.value = true;
      const formData = new FormData();
      formData.append('file', file);
      // 先将数据显示在页面中
      const reader = new FileReader();
      reader.onload = async (e) => {
        const buffer: any = e.target?.result;
        if (buffer) {
          const workbook = new ExcelJS.Workbook();
          await workbook.xlsx.load(buffer).then(async () => {
            const worksheet: any = workbook.getWorksheet(1);
            const headers: any[] = [];
            worksheet?.getRow(1).eachCell((cell: { value: any }) => {
              if (useUpload().isLetter(cell.value)) {
                headers.push(cell.value.toLowerCase());
              }
              else {
                headers.push(cell.value);
              }
            });
            const title = [
              'id',
              'area',
              'account',
              'printmonth',
              'invoice',
              'amount',
              'printflag',
              'operator',
              'created',
              'billmonth',
            ];
            // 拦截错误的表格
            if (!useUpload().areArraysEqualIgnoreOrder(title, headers)) {
              message.error('excel内表格的字段数或表头出错,上传失败！');
              loading.value = false;
              return;
            }
            // 上传到数据库
            await uploadData(formData).then(() => {
              message.success('上传成功！');
              // 移除文件
              handleRemove(file);
              // 更新数据
              getAllData();
            })
              .catch(() => {
                message.error('上传失败');
                // 重新更新数据，将原先显示在页面的数据撤回
                getAllData();
              });
            const newData = [];
            for (let rowNumber = 2; rowNumber <= worksheet?.rowCount; rowNumber++) {
              const rowData: any = {};
              const row = worksheet.getRow(rowNumber);
              row.eachCell((cell: { value: any }, colNumber: number) => {
                rowData[headers[colNumber - 1]] = cell.value;
              });
              data.value.push(rowData);
              newData.push(rowData);
              loading.value = false;
            }
          });
        }
      };
      reader.readAsArrayBuffer(file);
    }
    else {
      message.error('请上传execl文件！');
    }
  });
}

// 下载
async function downloadById(selectedId: number[]) {
  await useDownload().downloadById(selectedId);
  clearSelected();
  getAllData();
}

async function downloadAll() {
  await useDownload().downloadAll();
  getAllData();
}

async function downExcel() {
  await useDownload().downExcel();
}

// 修改打印状态
async function changePrint(ids: number[]) {
  loading.value = true;
  await updatePrintflag(ids).then(() => {
    message.success('修改成功');
    getAllData();
    clearSelected();
  })
    .finally(() => {
      loading.value = false;
    });
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            专票打印记录
          </div>
          <div class="add">
            <a-button v-auth="'v-add'" type="link" @click="add">
              新增
            </a-button>
            <a-button type="link" @click="selectAll">
              全选
            </a-button>
            <add_record :visible="visible" :get-visible="getVisible" :get-all-data="getAllData" />
          </div>
          <a-input-search
            v-model:value="value" placeholder="请输入关键字" enter-button style="width: 200px;"
            @search="onSearch"
          />
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-upload
            v-if="!isSelected" v-auth="'v-upload'" :file-list="fileList" :before-upload="beforeUpload"
            name="file" :multiple="false" action="" accept=".xlsx, .xls" :on-remove="handleRemove"
          >
            <a-button>
              <upload-outlined /> 点击选择文件
            </a-button>
          </a-upload>
          <a-button v-if="!isSelected" v-auth="'v-upload'" type="primary" @click="handleManualUpload">
            上传
          </a-button>
          <a-button v-if="isSelected" v-auth="'v-clear-choose'" type="primary" @click="clearChoose(selectedId)">
            批量删除
          </a-button>
          <a-button v-if="isSelected" v-auth="'v-print'" type="primary" @click="changePrint(selectedId)">
            修改打印状态
          </a-button>
          <a-button v-if="isSelected" v-auth="'v-download'" type="primary" @click="downloadById(selectedId)">
            选择性下载
          </a-button>
          <a-button v-auth="'v-download-all'" type="primary" @click="downloadAll">
            下载全部
          </a-button>
          <a-button v-auth="'v-upload'" type="primary" @click="downExcel">
            下载模板
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="content">
      <edit :loading="loading" class="v-table" :get-data-by-p="getAllData" />
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    position: sticky;
    top: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    background-color: #fff;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }
}

.content {
  display: flex;
  flex: 1;
  flex-direction: column;
  width: 100%;
  height: 95%;
  overflow: auto;
  overflow-y: auto;

  .v-table {
    flex-grow: 1;
    height: 100%;
    max-height: 100%;
    padding: 10px;
  }
}

.ant-upload-wrapper {
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
  height: 31px;
}
</style>
